package com.aiolos.weather.service.impl;

import com.aiolos.weather.service.CityDataService;
import com.aiolos.weather.util.XmlBuilder;
import com.aiolos.weather.vo.City;
import com.aiolos.weather.vo.CityList;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

@Service
public class CityDataServiceImpl implements CityDataService {

    /**
     * 获取城市列表
     * @return
     * @throws Exception
     */
    @Override
    public List<City> getCityList() throws Exception {
        //1. 读取xml文件
        Resource resource = new ClassPathResource("cityList.xml");
        BufferedReader br =
                new BufferedReader(new InputStreamReader(resource.getInputStream(),"utf-8"));
        StringBuffer stringBuffer = new StringBuffer();
        String line = "";

        while ((line = br.readLine()) != null){
            stringBuffer.append(line);
        }

        br.close();
        //2. 解析xml数据为POJO对象
        CityList cityList = (CityList)XmlBuilder.xmlStrToObj(CityList.class, stringBuffer.toString());
        return cityList.getCityList();
    }
}
